using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;

public class AsteroidController : MonoBehaviour
{
    [SerializeField] protected float movementSpeed = 1f; // 移动速度
    [SerializeField] protected float rotationSpeed = 20f; // 旋转速度

    protected Vector3 randomDirection;
    protected Vector3 randomAngle;

    protected PlayerController player;

    private int maxLittleAsteroids = 5;
    private int minLittleAsteroids = 1;

    [SerializeField] private GameObject littleAsteroid;
    
    protected int scoreValue = 10;
    
    protected GameManager gameManager;



    protected void Start()
    {
        player = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController>();
        gameManager = GameObject.FindGameObjectWithTag("GameController").GetComponent<GameManager>();

        randomDirection = SetRandomDirection();
        randomAngle = SetRandomAngle();
        
        StartCoroutine(WaitToDie());
    }

    void Update()
    {
        transform.Translate(randomDirection * (movementSpeed * Time.deltaTime), Space.World);
        // 随机旋转物体
        transform.Rotate(randomAngle * (rotationSpeed * Time.deltaTime));
    }

    private Vector3 SetRandomDirection()
    {
        float x = Random.Range(-1f, 1f);
        float y = Random.Range(-1f, 1f);
        return new Vector3(x, y, 0);
    }

    private Vector3 SetRandomAngle()
    {
        float x = Random.Range(-1f, 1f);
        float y = Random.Range(-1f, 1f);
        float z = Random.Range(-1f, 1f);
        return new Vector3(x, y, z);
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Bullet"))
        {
            Destroy(other.gameObject);
            DestroySelf();
        }

        if (other.CompareTag("Player"))
        {
            // TODO: 伤害Player
            player.DamageDealt();
            DestroySelf();
        }
    }

    protected virtual void DestroySelf()
    {
        gameManager.AddScore(scoreValue);
        CreateLittleAsteroids();
        Destroy(gameObject);
    }

    protected virtual void CreateLittleAsteroids()
    {
        int asteroidsToCreate = Random.Range(minLittleAsteroids, maxLittleAsteroids);

        for (int i = 0; i < asteroidsToCreate; i++)
        {
            Instantiate(littleAsteroid, transform.position, littleAsteroid.transform.rotation);
        }
    }
    
    IEnumerator WaitToDie()
    {
        yield return new WaitForSeconds(15f);
        Destroy(this.gameObject);
    }
}